// import type { UserProfileResponse } from "~/models/user";


// export const useUserProfile = () => useState<UserProfileResponse | null>("userProfile",()=>null);

export const useToken = () => useState<string>("token",()=>"");
export const setToken = (token:string) =>{
  const tokenCookie = useCookie("token");
  tokenCookie.value = token;
  useToken().value = token;
  console.log(`Token Cookie ${tokenCookie.value} || Token ${useToken().value}`)
  console.log(`Set Token ${token}`)
}
export const getToken = () =>{
  return useToken().value||useCookie("token").value;
}

const persistentDataMap : { [key: string]: () => Ref<any> } = {
 "useToken":useToken
 }
// [{key:"useToken",value:useToken}]
// Key 传入一个 token 

//保存状态
export const saveState = (key?:string) =>{
// 如果传入的key存在 则存储单个 反之对于持久化数据图中的全部存储一遍
  if(key){
      // key.slice(0,1).toUpperCase() = T 
      // key.slice(1).toLowerCase() = oken
      // useKey = useToken
      // 拼接字符串
      const stateKey = "use"+key.slice(0,1).toUpperCase()+key.slice(1).toLowerCase();
      // useKey = useToken
      // 尝试获取 状态对应的函数对象
      const stateFunc = persistentDataMap[stateKey];
      if(!stateFunc) {
        console.log(`persistentDataList 不存在${stateKey}`);
        return;
      }
      localStorage.setITem(key,JSON.stringify(stateFunc().value))
  }else{
    // console.log("保存所有状态");
    for(const key in persistentDataMap){
      if(Object.prototype.hasOwnProperty.call(persistentDataMap,key)){
        const stateFunc = persistentDataMap[key];  
        const setKey = key.toLowerCase().substring(3);
        try{
          localStorage.setItem(setKey,JSON.stringify(stateFunc().value))
        }catch(error){
          console.log(`设置${setKey}时出现错误:${error}`); 
        }
      }
    }
  }
}

// 加载状态
export const loadState = () =>{
  for(const key in persistentDataMap){
    if(Object.prototype.hasOwnProperty.call(persistentDataMap,key)){
      const stateFunc = persistentDataMap[key];
      const stateKey = key.toLowerCase().substring(3);
      try{
        const tempData = localStorage.getItem(stateKey)||''
        if(tempData){
          stateFunc().value = JSON.parse(tempData);
          // console.log(stateKey, '的本地存储数据获取成功', stateFunc().value);
        }
      }catch(error){
        console.log(`在获取${stateKey}的数据时出现错误`, error);
      }
    }
  }
}